package org.fastsyncer.connector.mysql;

import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.connector.common.DatabaseConstant;
import org.fastsyncer.connector.framework.AbstractDatabaseConnector;
import org.fastsyncer.connector.util.DatabaseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

public final class MysqlConnector extends AbstractDatabaseConnector {

    private static final Logger logger = LoggerFactory.getLogger(MysqlConnector.class);
    
    private static volatile MysqlConnector instance = null;

    private MysqlConnector() {
    }

    public static MysqlConnector getInstance() {
        if (null == instance) {
            synchronized (MysqlConnector.class) {
                if (null == instance) {
                    instance = new MysqlConnector();
                }
            }
        }
        return instance;
    }
    
    @Override
    public BaseInfo getBaseInfoConnector(DatabaseConfig config, String queryFilter) {
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate(config);
        BaseInfo connector;
        try {
            String table = config.getTable().toUpperCase();
            // 查询元信息 SELECT * FROM USER LIMIT 0
            String metaSQL = new StringBuilder().append("SELECT * FROM ").append(table).append(DatabaseConstant.MYSQL_PAGE_SQL_NULL).toString();
            // 求数据总量 SELECT * FROM USER WHERE ID='123'
            String countSQL = new StringBuilder().append("SELECT * FROM ").append(table).append(queryFilter).toString();
            connector = DatabaseUtil.getDataSourceConnector(jdbcTemplate, metaSQL, countSQL);
        } catch (Exception e) {
            logger.error("Failed to baseInfo, Please make sure config is right." + e.getLocalizedMessage());
            connector = new BaseInfo();
        }finally {
            // 释放连接
            this.close(jdbcTemplate);
        }
        return connector;
    }
    
    @Override
    public StringBuilder getPageSQL(DatabaseConfig config, StringBuilder sql) {
        // Mysql 分页查询
        return sql.append(DatabaseConstant.MYSQL_PAGE_SQL);
    }

}
